<script setup>
import ContentContainer from "@/views/feedback/design/components/contentContainer.vue";
import IssueItem from "@/views/feedback/design/components/issueItem.vue";
import {designRules} from "@/utils/configs.js";

const props = defineProps({
  listData: {
    type:Array,
    default: () => []
  },
  surveyData: {
    type:Object,
    default: () => ({})
  }
})
const formData = ref({})
const formRules = ref({})
const formRef = ref(null)

const validateArrayField = (rule, value, callback) => {
  if (value.length === 0) {
    return callback(new Error('至少需要有一项'));
  } else {
    callback();
  }
};
watchEffect(()=>{
  props.listData.forEach(item=>{
    // 生成formData数据
    if(item.type ==='multiple-check'){
      formData.value[item.field] = []
    }else{
      formData.value[item.field] = ''
    }
    // 生成formRules数据
    let ruleList = [];
    if(item.isRequired === 'Y'){
      if(['image-upload','file-upload'].includes(item.type)){
        ruleList.push({ required: true, message:'请上传文件',  trigger: ['blur','change'] })
      }else{
        ruleList.push({ required: true, message:'请填写或选择',  trigger: ['blur','change'] })
      }
      if(item.type === 'multiple-check'){
        ruleList.push({ validator: validateArrayField,   trigger: ['blur','change'] })
      }
    }
    if(item.needValid === 'Y'){
      let valid = designRules.filter(obj=>item.validateArr.includes(obj.value))
      valid =valid.map(obj=>({
         message:`格式应${obj.label}`,
         pattern: obj.pattern,
         trigger: ['blur','change']
      }))
      ruleList.push(...valid)
    }
    formRules.value[item.field] = ruleList
  })
})
const isFinish = ref(false)
const onSubmit = async ()=>{
  await formRef.value.validate()
  isFinish.value = true;
}
</script>

<template>
  <div class="form-box">
    <el-result
        v-if="isFinish"
        icon="success"
        title="填报完成"
        :sub-title="surveyData.surFinish"
    >
      <template #extra>
        <el-button @click="isFinish=false" type="primary">返回</el-button>
      </template>
    </el-result>
    <ContentContainer v-else :list-data="listData" :survey-data="surveyData" class="flex-1 min-w-[0] border-x-[4px] border-x-solid border-[#eee]">
      <el-form  :model="formData" ref="formRef" :rules="formRules">
        <issue-item
            v-for="(item,index) in listData"
            :key="index"
            :showScore="surveyData.showScore === 'Y'"
            :showIndex="surveyData.showIndex === 'Y'"
            :showType="surveyData.showType === 'Y'"
            :editMode="false"
            :form-data="formData"
            :drawingList="listData"
            :element="item"
            :index="index"
        />
        <el-row type="flex" justify="center">
          <el-button type="primary"  @click="onSubmit">确定</el-button>
        </el-row>
      </el-form>
    </ContentContainer>
  </div>
</template>
<style scoped lang="scss">
</style>
